#
# "@(#) $Id: PlaylistView.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from LibraryView import *
from PlaylistViewItem import *
from RemoteTrackDrag import *
from Services.Downloader import *

def cleanup(fileList):
	#print "cleanup",fileList
	files = []
	for file in fileList:
		files.append(unikode(file).encode('ISO-8859-1'))
	return files

class PlaylistView(LibraryView):
	def __init__(self,container):
		LibraryView.__init__(self,container,'playlist')
	
	def bulkEditEnd(self):
		self.bulkEdit = False
		self.loadPlaylistItems()

	def setCurrentPlaylist(self):
		pass

	def loadHeaders(self):
		headers = [" ","",i18n("Song Name"),i18n("Time"),i18n("Artist"),i18n("Album"),i18n("Genre"),i18n("My Rating"),i18n("Play Count"),i18n("Last Played")]
		widths = [40,20,220,40,120,180,80,80,70,130]
		for index in xrange(0,len(headers)):
			self.addColumn(headers[index],widths[index])
		self.setShowSortIndicator(True)
		self.setFullWidth(True)
		self.setColumnAlignment(8,Qt.AlignCenter)
		self.indexColumn = 1
		self.ratingColumn = 7
		sortColumn = self.settings.get('Playlist Sort Column',1)
		sortAscending = self.settings.get('Playlist Sort Ascending',True)
		self.setSorting(sortColumn,sortAscending)
		QObject.connect(self.header(),SIGNAL("indexChange(int,int,int)"),self.columnIndexChanged)
		QObject.connect(self.header(),SIGNAL("sizeChange(int,int,int)"),self.columnSizeChanged)
		QObject.connect(self,SIGNAL('selectionChanged()'),self.selectionChanged)
		self.loadHeaderSizes('Playlist Header Widths')
		self.loadHeaderOrdering('Playlist Header Map')
		self.setDropHighlighter(False)
		self.setDropVisualizer(True)

	def loadTracks(self):
		pass

	def setSearchType(self,searchType):
		self.searchType = searchType
		self.loadPlaylistItems()

	def setSearchText(self,searchText):
		self.searchText = searchText
		self.loadPlaylistItems()

	def setPlaylist(self,playlist):
		self.playlistName = playlist.name
		self.playlist = playlist
		print type(playlist), "TYPE"
		self.playlist.connect(PYSIGNAL("addedTrack"),self.addedTrack)
		self.playlist.connect(PYSIGNAL("aboutToRemoveTrack"),self.aboutToRemoveTrack)
		#self.playlist.connect(PYSIGNAL("removedTrack"),self.removedTrack)
		self.playlist.connect(PYSIGNAL("shuffled"),self.shuffled)
		self.loadPlaylistItems()

	def addedTrack(self,playlist,trackID):
		if playlist==self.playlist:
			track = playlist.trackWithTrackID(trackID)
			if track:
				index = len(self.playlist.tracks)
				if self.matchesSearch(track):
					self.loadTrackItemForIndex(track,index)
				self.emitCurrentEnabledSortedTracks()
				self.emit(PYSIGNAL("changed"),(self, None))
			else:
				print "PlaylistView.addedTrack: can't find trackID",trackID
	
	def aboutToRemoveTrack(self,playlist,trackID):
		if playlist==self.playlist:
			track = playlist.trackWithTrackID(trackID)
			item = self.firstChild()
			removedIndex = 9999
			while item:
				if item.track()==track:
					removedIndex = item.index
					self.takeItem(item)
					del item
					break
				item = item.itemBelow()
			item = self.firstChild()
			while item:
				if item.index>=removedIndex:
					item.setIndex(item.index-1)
				item = item.itemBelow()
			self.emit(PYSIGNAL("changed"),(self, None))

	def removeSelectedItems(self):
		trackIDs = self.selectedTrackIDs()
		self.playlist.removeTrackIDs(trackIDs)
		self.emitCurrentEnabledSortedTracks()
		self.emit(PYSIGNAL("changed"),(self, None))

	def loadPlaylistItems(self):
		#print "loading playlist items"
		self.clear()
		index = 1
		tracks = self.playlist.tracks
		self.setUpdatesEnabled(False)
		self.blockSignals(True)
		for track in tracks:
			if track:
				if self.matchesSearch(track):
					self.loadTrackItemForIndex(track,index)
				index = index+1
		self.blockSignals(False)
		self.setUpdatesEnabled(True)
		self.update()
		self.emitCurrentEnabledSortedTracks()
		self.emit(PYSIGNAL("changed"),(self, None))

	def loadTrackItemForIndex(self,track,index):
		item = PlaylistViewItem(self,track,index)

	def canBurn(self):
		return True

	def canShowLocation(self):
		return True

	def canGetInfo(self):
		return True
	
	def canPlay(self):
		return True
	
#	def selectedItem(self,item):
#		self.emit(PYSIGNAL("selectedItem"),(item,None))
		
	def selectionChanged(self):
		self.emit(PYSIGNAL("selectedItem"),(self.firstSelectedItem(),None))

	def refresh(self):
		self.loadPlaylistItems()

	def doSelectionChanged(self):
		LibraryView.doSelectionChanged(self)
		self.emit(PYSIGNAL("selectionChanged"),(self,None))

	def setSorting(self,column,ascending):
		if column==self.indexColumn:
			ascending = True
		KListView.setSorting(self,column,ascending)
		self.settings['Playlist Sort Column'] = column
		self.settings['Playlist Sort Ascending'] = not not ascending
		self.emitCurrentEnabledSortedTracks()

	def columnIndexChanged(self,section,fromIndex,toIndex):
		self.saveHeaderOrdering('Playlist Header Map')
	
	def columnSizeChanged(self,section,oldSize,newSize):
		self.saveHeaderSizes('Playlist Header Widths')

	#
	# drop methods used by Qt
	#
	def contentsDragEnterEvent(self,event):
		if TrackDrag.canDecode(event):
			#print "dropping Qt",event
			event.accept(True)
		else:
			LibraryView.contentsDragEnterEvent(self,event)

	def shuffled(self):
		self.loadPlaylistItems()
	
	def contentsDropEvent(self,event):
		if TrackDrag.canDecode(event):
			drag = TrackDrag.decode(event)
			sourcePlaylistName = drag['Playlist']
			sourcePlaylist=self.library.playlistWithName(sourcePlaylistName)
			trackIDs = drag['TrackIDs']
			if sourcePlaylistName==self.playlistName:
				if self.sortColumn()==self.indexColumn and (self.searchText==None or len(self.searchText)==0):
					pos = self.contentsToViewport(event.pos())
					item = self.itemAt(pos)
					if item==None:
						self.playlist.shuffle(trackIDs,self.lastChild().index)
					else:
						self.playlist.shuffle(trackIDs,item.index-1)
			else:
				self.playlist.addTrackIDs(trackIDs)
				trash = self.library.playlistWithName('Trash')
				library = self.library.playlistWithName('Library')
				if sourcePlaylist==trash:
					trash.removeTrackIDs(trackIDs)
					library.addTrackIDs(trackIDs)
		elif RemoteTrackDrag.canDecode(event):
			drag = RemoteTrackDrag.decode(event)
			tracks = []
			for trackplist in drag['Tracks']:
				track = Track()
				track.setPList(trackplist)
				tracks.append(track)
			Downloader.singleton().downloadTracks(tracks,self.playlist,self.library)
		elif QUriDrag.canDecode(event):
			uris = QStringList()
			if QUriDrag.decodeLocalFiles(event,uris):
				uris = cleanup(uris)
				self.library.importFiles(removeDuplicates(uris),self.playlist)

	#
	# drop methods used by KDE
	#	
	def acceptDrag(self,event):
		if TrackDrag.canDecode(event): return True
		if RemoteTrackDrag.canDecode(event): return True
		return LibraryView.acceptDrag(self,event)

